$(function() {

		$.ajaxSetup({
			async: false
		});

		var initialize = function() {

			$('#rbody').html('');

			var temple = "<tr><td class=center><span id=rName>{{role}}</span><input type=hidden id='id' value={{id}}></td><td class=center><button id='priBtn' class='btn btn-warning btn-small'>授权</button></td><td class=center><i id=editIcon style='cursor:pointer;' class='icon-pencil bigger-150'></i>&nbsp;&nbsp;&nbsp;<i id='deleteIcon' style='cursor:pointer;' class='icon-trash  bigger-150'></i></td></tr>";
			//var temple = "<tr><td class=center><span id=rName>{{role}}</span><input type=hidden id='id' value={{id}}></td><td class=center><button id='priBtn' class='btn btn-warning btn-small'>授权</button></td><td class=center><i id='deleteIcon' class='icon-trash  bigger-150'></i></td></tr>";


			//获取角色名
			$.ajax({
				url: '/api/role?',
				type: 'get',
				data: {'_t':new Date().getTime()},
				success: function(data) {
					if(data == 'noPrivilege'){
						//alert('noPrivilege');
						data = [];
					}
					$.each(data, function(i, role) {
						if (data == "") {
							$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>没有相关信息</div>");
							return;
						} else {
							$('#tip').html("");
						}

						var data = {
							role: role.roleName,
							id: role.id
						};

						var $html = $(Mustache.to_html(temple, data));

						$('#rbody').append($html);

						//定义删除角色操作
						$html.find('#deleteIcon').click({
							html: $html
						}, function(e) {

							var $html = $(e.data.html);
							deleteRole($html);

						});

						//定义编辑角色操作
						$html.find('#editIcon').click({
							html: $html
						}, function(e) {
							var $html = $(e.data.html);
							var rolename = $html.find('#rName').val();
							var id = $html.find('#id').val();

							var editData = {
								role: role.roleName,
								id: id
							};

							addRole(editData);
						});

						//定义授权操作
						$html.find('#priBtn').click({
							role: role
						}, function(e) {
							authorizeRole(e.data.role);
						});

					});
				}
			});
			// $.get('/api/role', function(data, status) {
			// 	if(data == 'noPrivilege'){
			// 		//alert('noPrivilege');
			// 		data = [];
			// 	}
			// 	if (status == 'success') {
			// 		$.each(data, function(i, role) {
			// 			if (data == "") {
			// 				$('#tip').html("<div class='alert alert-warning' style='margin-top:-20px;'>没有相关信息</div>");
			// 				return;
			// 			} else {
			// 				$('#tip').html("");
			// 			}

			// 			var data = {
			// 				role: role.roleName,
			// 				id: role.id
			// 			};

			// 			var $html = $(Mustache.to_html(temple, data));

			// 			$('#rbody').append($html);

			// 			//定义删除角色操作
			// 			$html.find('#deleteIcon').click({
			// 				html: $html
			// 			}, function(e) {

			// 				var $html = $(e.data.html);
			// 				deleteRole($html);

			// 			});

			// 			//定义编辑角色操作
			// 			$html.find('#editIcon').click({
			// 				html: $html
			// 			}, function(e) {
			// 				var $html = $(e.data.html);
			// 				var rolename = $html.find('#rName').val();
			// 				var id = $html.find('#id').val();

			// 				var editData = {
			// 					role: role.roleName,
			// 					id: id
			// 				};

			// 				addRole(editData);
			// 			});

			// 			//定义授权操作
			// 			$html.find('#priBtn').click({
			// 				role: role
			// 			}, function(e) {
			// 				authorizeRole(e.data.role);
			// 			});

			// 		});
			// 	}

			// });
		}

		initialize();

		//新增加角色
		$('#rbtn').click(function() {
			addRole(null);
		});

		//添加或更新角色
		var addRole = function(roleData) {

			$('#roleAdd').modal('show');
			$("#nameMsg").html("");
			if (roleData != null) {
				$('#myModalLabel11').html('编辑角色');
				$('#rolename').val(roleData.role);
				$('#roleId').val(roleData.id);
				//console.info(roleData.id);
			} else{
				$('#myModalLabel11').html('添加角色');
				$('#rolename').val('');
			}
				

			$('#roleAddSave').unbind('click');
			$('#roleAddSave').bind('click', function() {
					var rolename = $('#rolename').val();
					var roleId = $('#roleId').val();
					// console.info('info',roleId);
					var checkToReturn = false;

					$.get('/api/role', function(data) {
						
						var type = roleData != null ? 'PUT' : 'POST';

						$.each(data, function(i, role) {
							if (rolename == role.roleName) {
								if(type == 'PUT' && roleData.id == role.id){
									checkToReturn = false;
								} else {
									checkToReturn = true;
								}
							}
						});
						if (rolename == "") {
							$("#nameMsg").html("请填写角色名");
							$("#nameMessage").css("display","block");
			 				return;
						}else{
							$("#nameMessage").css("display","none");
						}
						if (checkToReturn) {
							$("#nameMessage").css("display","block");
							$("#nameMsg").html("角色名已存在,请重新输入");
			 				return;
						}else{
							$("#nameMessage").css("display","none");
						}
						var data = roleData != null ? {
							id: roleData.id,
							roleName: rolename
						} : {
							roleName: rolename
						};
						$.ajax({
							url: '/api/role',
							type: type,
							data: data,
							success: function(result) {
								if(result == 'noPrivilege'){
									bootbox.alert('您没有权限,操作失败！');
									return;
								}
								if (type === 'POST') {
									bootbox.alert('添加角色成功！');
								} else if (type === 'PUT') {
									bootbox.alert('更新角色成功！');
								}
								$('#roleAdd').modal('hide');
								initialize();
							},
							error: function(result) {
								$('#roleAdd').modal('hide');

								if (roleData != null)
									bootbox.alert('更新角色失败！');
								else
									bootbox.alert('添加角色失败！');
							}


						});
					});
				});
			}

	//删除角色
	var deleteRole = function(html) {
		bootbox.confirm("确定删除吗？", function(result) {
			if(!result){
				return;
			}
			var $html = $(html);
			var rolename = $html.find('#rName').html();
			var id = $html.find('#id').val();

			$.get('/api/userRole/' + id, function(data) {
					var delData = {
						id: id
					};
					// console.info('data',data);

					if (data != null && data.length != 0) {
						bootbox.alert('该角色存在用户，不能删除！');
						return;
				  }
				  $.ajax({
						url: '/api/role',
						type: 'DELETE',
						data: delData,
						success: function(result) {
							if(result == 'noPrivilege'){
								bootbox.alert('您没有权限,操作失败！');
								return;
							}
							initialize();
						},
						error: function(result) {
							bootbox.alert("删除角色失败!");
						}
					});				
			});

		});
	};



	$("#roleAuthCommit").click(function() {
		var role = $("#saveRole").val();
		// console.info("role = " + role);
		var checkData = checkRole(role);
		// console.info("checkData = ");
		// console.info(checkData);
		var resource = [];
		var $trHtmls = $('#authorizeBody').find('tr');
		$.each($trHtmls, function(i, trHtml) {

			//var checked = $(trHtml).find('#choose').is(':checked');
			// console.info("第" + i + "行：checked ");
			// console.info(checked);

			//if (checked) {
				var resId = $(trHtml).find('#resId').val();
				var resName = $(trHtml).find('#resName').html();
				var url = $(trHtml).find('#url').val();

				// var $opers = $(trHtml).find('#oper');
				var $opers = $(trHtml).find("td[name='opera']")
				var operation = new Array();

				$.each($opers, function(j, oper) {
					var operChecked = $(oper).find(':checkbox').is(':checked');

					if (operChecked) {
						var hiddenInput = $(oper).find(':hidden').val();
						operation.push(hiddenInput);
					}
				});

				$.each(operation, function(i, operate) {
					var data = {
						opername: resName,
						oper: operate,
						resource: url,
						resId : resId
					};

					resource.push(data);
				});
			//}
		});

		var resourceData = {
			role: role,
			resource: resource
		};
		// console.info("======postData========");
		// console.info(resourceData);

		var type = checkData.length != 0 ? 'PUT' : 'POST';
		//console.info(type);
		if(type == 'POST' && resource.length == 0){
			bootbox.alert('请勾选资源操作！');
			return;
		}

		$.ajax({
			url: '/api/roleresource', 
			type: type,
			data: resourceData,
			async: false,
			success: function(result) {
				$('#roleAuthorize').modal('hide');
				bootbox.alert("角色授权成功!");
				initialize();
			},
			error: function(result) {
				$('#roleAuthorize').modal('hide');
				bootbox.alert("角色授权失败!");
				initialize();
			}
		});

	});

	//给角色授权
	var authorizeRole = function(role) {
		$("#saveRole").val(role.id);//授权时吧id存放进去
		$('#roleAuthorize').modal('show');
		var checkData = checkRole(role.id);
		// console.info('rolerole:', role);
		// console.info('checkData:::::',checkData);

		initializeAuth(checkData);

	};

	var initializeAuth = function(checkData) {
		$('#authorizeBody').html('');
		//<td class=center><input  id=choose type=checkbox><span class=lbl></span></td>
		var template = "<tr>" +
			"<td class=center><span id=resName>{{resource}}</span></td><input type=hidden id=resId value={{resId}}><input type=hidden id=url value={{url}}></td>" +
			"<td id=oper1 name = opera class=center><input type=checkbox><span class=lbl></span>{{oper1}}<input id=hioper  type=hidden value={{operation1}}></td>" +
			"<td id=oper2 name = opera class=center><input type=checkbox><span class=lbl></span>{{oper2}}<input id=hioper type=hidden value={{operation2}}></td>" +
			"<td id=oper3 name = opera class=center><input type=checkbox><span class=lbl></span>{{oper3}}<input id=hioper type=hidden value={{operation3}}></td>" +
			"<td id=oper4 name = opera class=center><input type=checkbox><span class=lbl></span>{{oper4}}<input id=hioper type=hidden value={{operation4}}></td></tr>";

		//拿到资源
		$.get('/api/resource', function(data, status) {
			if(data == 'noPrivilege'){
				bootbox.alert('您没有权限,操作失败！');
				return;
			}
			if (status == 'success') {

				// var resources = data.resource;
				// var opers = data.operation;

				//console.info("====data=====");
				//console.info(data);

				$.each(data, function(i, resource) {

					if (resource.resName == "")
						return;

					var templateData = {
						resource: resource.resName,
						url: resource.resUrl,
						resId: resource.id,
						oper1: "增加",
						oper2: "查询/导出",
						oper3: "修改",
						oper4: "删除",
						operation1: 'post',
						operation2: 'get',
						operation3: 'put',
						operation4: 'delete'
					};

					var $html = $(Mustache.to_html(template, templateData));

					$('#authorizeBody').append($html);

				});
			}
		});

		if (checkData.length != 0) {
			// console.info('checkData:::::::::::::::::::::::', checkData)
			var $trHtmls = $('#authorizeBody').find('tr');
			$.each($trHtmls, function(i, trHtml) {
				// console.info(trHtml);

				var resName = $(trHtml).find('#resName').html();
				var resId = $(trHtml).find('#resId').val();

				//console.info("resName = " + resName + resId);

				var url = $(trHtml).find('#url').val();
				var $opers = $(trHtml).find("td[name='opera']");

				$.each(checkData, function(k, data) {
					//console.info('hahahhhahha:',data.operation);
					if (data.resId == resId) {
						$(trHtml).find('#choose').attr("checked", true);
						$.each($opers, function(m, operation) {


							if ($(operation).find('#hioper').val() == data.operation) {
								$(operation).find(':checkbox').attr("checked", true);
							}
						})

					}
				});

			});

		}

	};

	//检查角色是否已授权
	var checkRole = function(checkRole) {
		var reData = [];
		$.get('/api/roleresource', function(data, status) {
			if (status == 'success') {

				$.each(data, function(i, role) {
					if (role.roleId == checkRole) {

						reData.push(role);
						// console.info('inside');
						// console.info(reData);
					}
				});

			}
		});

		// console.info(reData);
		return reData == [] ? null : reData;
	};

});